<template>
  <div class="honor-management">
    <div class="header">
      <h2>荣誉管理</h2>
      <el-button v-permission="['editHonor']" type="primary" @click="showAddDialog">新增荣誉</el-button>
    </div>

    <div class="honor-list">
      <el-card 
        v-for="(honor, index) in honors" 
        :key="index" 
        class="honor-card"
        :class="{ disabled: honor.status === 0 }"
      >
        <div class="card-content">
          <div class="honor-image">
            <img :src="honor.image" :alt="honor.name">
          </div>
          <div class="honor-info">
            <h3>{{ honor.name }}</h3>
            <div class="status">
              <el-tag :type="honor.status ? 'success' : 'info'">
                {{ honor.status ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="card-actions"  v-permission="['editHonor']">
          <el-button size="small" @click="editHonor(index)">编辑</el-button>
          <el-button 
            size="small" 
            :type="honor.status ? 'warning' : 'success'"
            @click="toggleStatus(index)"
          >
            {{ honor.status ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteHonor(index)">删除</el-button>
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      width="40%"
    >
      <el-form :model="currentHonor" label-width="100px">
        <el-form-item label="荣誉名称" required>
          <el-input v-model="currentHonor.name"></el-input>
        </el-form-item>
        <el-form-item label="荣誉图片">
         <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'Authorization': `Bearer ${getToken()}` }"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="currentHonor.image" :src="currentHonor.image" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentHonor.status"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHonor">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { getHonorList, addHonor, updateHonor, delHonor} from '@/api/honor'
    const honors = ref([])
    const loading = ref(false)

    // 获取荣誉列表
    const fetchHonors = async () => {
      try {
        loading.value = true
        const res = await getHonorList()
        honors.value = res.data.map(item => ({
          id: item.id,
          name: item.honorName,
          image: item.avatar,
          status: parseInt(item.status)
        }))
      } catch (error) {
        ElMessage.error('获取荣誉列表失败')
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      fetchHonors()
    })
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增荣誉')
    const currentHonor = reactive({
      id: null,
      name: '',
      image: '',
      status: '1'
    })
    const isEditing = ref(false)
    const editingIndex = ref(null)

    const showAddDialog = () => {
      dialogTitle.value = '新增荣誉'
      Object.assign(currentHonor, {
        id: null,
        name: '',
        image: '',
        status: '1'
      })
      isEditing.value = false
      dialogVisible.value = true
    }

    const editHonor = (index) => {
      dialogTitle.value = '编辑荣誉'
      Object.assign(currentHonor, { ...honors.value[index] })
      currentHonor.status = currentHonor.status.toString()
      isEditing.value = true
      editingIndex.value = index
      dialogVisible.value = true
    }

    const handleImageChange = (file) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        currentHonor.image = e.target.result
      }
      reader.readAsDataURL(file.raw)
    }

    const saveHonor = async () => {
      if (!currentHonor.name) {
        ElMessage.error('请输入荣誉名称')
        return
      }
      if (!currentHonor.image) {
        ElMessage.error('请上传荣誉图片')
        return
      }

      try {
        const params = {
          honorName: currentHonor.name,
          avatar: currentHonor.image,
          status: currentHonor.status.toString()
        }

        if (isEditing.value) {
          params.id = currentHonor.id
          await updateHonor(params)
          ElMessage.success('更新成功')
        } else {
          await addHonor(params)
          ElMessage.success('新增成功')
        }
        
        dialogVisible.value = false
        await fetchHonors()
      } catch (error) {
        ElMessage.error(isEditing.value ? '更新失败' : '新增失败')
      }
    }

    const toggleStatus = async (index) => {
      try {
        const honor = honors.value[index]
        await updateHonor({
          id: honor.id,
          status: honor.status ? '0' : '1',
          honorName: honor.name,
          avatar: honor.image
        })
        honor.status = honor.status ? 0 : 1
        ElMessage.success('状态已更新')
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    const deleteHonor = async (index) => {
      try {
        await ElMessageBox.confirm('确定要删除该荣誉吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delHonor({id: honors.value[index].id})
        await fetchHonors()
        ElMessage.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  console.log(response, URL.createObjectURL(file.raw))
  currentHonor.image = response.data
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }

  return isImage && isLt2M
}
</script>

<style scoped>
.honor-management {
  padding: 24px;
  min-height: calc(100vh - 64px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
}

.header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.honor-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.honor-card {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12);
}

.honor-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.honor-card.disabled {
  opacity: 0.6;
  filter: grayscale(50%);
}

.card-content {
  display: flex;
  padding: 16px;
}

.honor-image {
  width: 120px;
  height: auto;
  margin-right: 16px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.honor-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.honor-card:hover .honor-image img {
  transform: scale(1.05);
}

.honor-info {
  flex: 1;
  min-width: 0;
}

.honor-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status {
  margin-top: 8px;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f9fafc;
  border-top: 1px solid #ebeef5;
}

.card-actions .el-button {
  flex: 1;
  margin: 0 4px;
}

@media (max-width: 768px) {
  .card-content {
    flex-direction: column;
  }
  
  .honor-image {
    width: 100%;
    margin-right: 0;
    margin-bottom: 12px;
  }

  .card-actions {
    flex-direction: column;
    gap: 8px;
  }

  .card-actions .el-button {
    width: 100%;
    margin: 0;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.honor-card {
  animation: fadeIn 0.4s ease-out;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
</style>